{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1b6aee35-252a-4e13-9e7b-67b050cfb781",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2 as cv\n",
    "import os\n",
    "\n",
    "out_folder = 'face_img'#建立文件夹，用于保存经过处理后的面部图片信息\n",
    "if not os.path.exists(out_folder):\n",
    "    os.mkdir(out_folder)\n",
    "\n",
    "# os.listdir 返回指定目录下的所有文件和文件夹名称\n",
    "# 如果不指定目录，则默认为python文件所在目录\n",
    "l = []\n",
    "for f in os.listdir():\n",
    "    if \".jpg\" not in f:  # 如果不是图片，则跳过\n",
    "        continue\n",
    "\n",
    "    l.append(f)  # 将图片名报存在一个列表中\n",
    "\n",
    "for i in l:\n",
    "    img = cv.imread(i)\n",
    "    img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n",
    "    img_gray = cv.equalizeHist(img_gray)  # 对图像进行直方图增强\n",
    "\n",
    "    # 1. 创建级联分类器\n",
    "    face_cascade = cv.CascadeClassifier()\n",
    "    # 2. 引入训练好的可用于人脸识别的级联分类器模型\n",
    "    face_cascade.load(\"haarcascade_frontalface_alt.xml\")\n",
    "    # 3. 用此级联分类器识别图像中的所有人脸信息，返回一个包含有所有识别的人联系系的列表\n",
    "    # 列表中每一个元素包含四个值：面部左上角的坐标(x,y) 以及面部的宽和高(w,h)\n",
    "    faces = face_cascade.detectMultiScale(img_gray)\n",
    "\n",
    "    # 4. 获取所有的面部信息并保存为.jpg图片\n",
    "    for (x, y, w, h) in faces:\n",
    "        # cv.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)\n",
    "        cv.imwrite(os.path.join(out_folder, '{}.jpg'.format(i.split('.')[0]+'.'+i.split('.')[1])),\n",
    "                   img[y:y+h+1, x:x+w+1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12929975-e458-43c1-a09e-160af3d2ae4f",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
